// 文件路径: lib/login_screen.dart

import 'package:film/controller/login_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class LoginScreen extends StatelessWidget {
  // 使用Get.put()来实例化控制器，或者在路由绑定中完成
  final LoginController controller = Get.put(LoginController());

  LoginScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 背景色
      backgroundColor: Colors.red,
      body: SingleChildScrollView(
        child: SafeArea(
          child: Column(
            children: [
              // 返回
              Align(
                alignment: Alignment.topLeft,
                child: IconButton(
                    icon: const Icon(Icons.arrow_back, color: Colors.white),
                    onPressed: () {
                      Get.back();
                    }),
              ),
              // 头像
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 30.0),
                child: Column(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Image.asset(
                        // 使用网络图片作为示例
                        'assets/images/all.png', // 这是你图片中的URL
                        width: 90,
                        height: 90,
                        fit: BoxFit.cover,
                      ),
                    ),
                    const SizedBox(height: 30),
                    // 主体表单卡片
                    _buildFormCard(),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建表单卡片
  Widget _buildFormCard() {
    return Container(
      padding: const EdgeInsets.all(24.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.0),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 5),
          )
        ],
      ),
      // Obx包裹需要根据状态动态改变的UI部分
      child: Obx(
        () => Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 邮箱/手机号输入框
            _buildTextField(
              textController: controller.emailController,
              hintText: '邮箱',
              icon: Icons.email,
            ),
            const SizedBox(height: 16),

            // 密码输入框
            _buildTextField(
              textController: controller.passwordController,
              hintText: '密码',
              icon: Icons.lock,
              isPassword: true,
              obscureText: controller.isPasswordObscured.value,
              onToggleVisibility: controller.togglePasswordVisibility,
            ),

            // --- 动态添加的注册相关输入框 ---
            // 使用AnimatedSize和AnimatedOpacity可以实现平滑的出现/消失动画
            AnimatedSize(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              child: Column(
                children: [
                  if (!controller.isLoginMode.value) ...[
                    const SizedBox(height: 16),
                    // 确认密码输入框
                    _buildTextField(
                      textController: controller.confirmPasswordController,
                      hintText: '确认密码',
                      icon: Icons.lock,
                      isPassword: true,
                      obscureText: controller.isConfirmPasswordObscured.value,
                      onToggleVisibility: controller.toggleConfirmPasswordVisibility,
                    ),
                    const SizedBox(height: 16),
                    // 验证码
                    _buildTextField(
                      textController: controller.verificationCodeController,
                      hintText: '验证码',
                      icon: Icons.attach_email,
                      isVerificationCode: true,
                      obscureText: controller.isConfirmPasswordObscured.value,
                      onToggleVisibility: controller.toggleConfirmPasswordVisibility,
                    ),
                    const SizedBox(height: 16),
                    // 邀请码输入框
                    _buildTextField(
                      textController: controller.invitationCodeController,
                      hintText: '邀请码 (可不填)',
                      icon: Icons.group_add_outlined,
                    ),
                  ],
                ],
              ),
            ),
            const SizedBox(height: 12),

            // 忘记密码
            Align(
              alignment: Alignment.center,
              child: TextButton(
                onPressed: () {
                  Get.toNamed('/forgotPassword');
                },
                child: const Text(
                  '忘记密码?',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
            ),
            const SizedBox(height: 10),

            // 登录/注册按钮
            _buildActionButton(),
            const SizedBox(height: 10),

            // 切换模式的文本按钮
            TextButton(
              onPressed: controller.toggleFormMode,
              child: Text(
                controller.isLoginMode.value ? '注册' : '登录',
                style: const TextStyle(
                  color: Colors.grey,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建通用输入框
  Widget _buildTextField({
    required TextEditingController textController,
    required String hintText,
    required IconData icon,
    bool isPassword = false,
    bool obscureText = false,
    bool isVerificationCode = false,
    VoidCallback? onToggleVisibility,
  }) {
    return TextField(
      controller: textController,
      obscureText: obscureText,
      decoration: InputDecoration(
        hintText: hintText,
        hintStyle: const TextStyle(color: Colors.grey),
        prefixIcon: Icon(icon, color: Colors.grey),
        suffixIcon: isVerificationCode
            ? Obx(
                () => GestureDetector(
                  // 当按钮可用时，调用 _startTimer；否则不响应点击
                  onTap: controller.isButtonEnabled.value ? controller.sendEmail : null,
                  child: IntrinsicWidth(
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10), // 左右对称padding
                      alignment: Alignment.centerRight,
                      child: Text(
                        // 根据按钮是否可用，显示不同文本
                        controller.isButtonEnabled.value ? '发送验证码' : '${controller.countdown}秒后重发',
                        style: TextStyle(color: Colors.grey),
                      ),
                    ),
                  ),
                ),
              )
            : isPassword
                ? IconButton(
                    icon: Icon(
                      obscureText ? Icons.visibility_off : Icons.visibility,
                      color: Colors.grey,
                    ),
                    onPressed: onToggleVisibility,
                  )
                : null,
        filled: true,
        fillColor: Colors.grey[200],
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(50.0),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      ),
    );
  }

  /// 构建主操作按钮（登录/注册）
  Widget _buildActionButton() {
    return SizedBox(
      width: 150,
      child: Obx(
        () => ElevatedButton(
          onPressed: controller.isLoading.value
              ? null
              : () {
                  // 加载中时禁用按钮
                  if (controller.isLoginMode.value) {
                    controller.login();
                  } else {
                    controller.register();
                  }
                },
          style: ElevatedButton.styleFrom(
            backgroundColor: const Color(0xFF34495e),
            padding: const EdgeInsets.symmetric(vertical: 10),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(50),
            ),
          ),
          child: controller.isLoading.value
              ? const SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    color: Colors.white,
                    strokeWidth: 2,
                  ),
                )
              : Text(
                  controller.isLoginMode.value ? '登录' : '注册',
                  style: const TextStyle(fontSize: 16, color: Colors.white),
                ),
        ),
      ),
    );
  }
}
